# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout, QStackedWidget
from qfluentwidgets import SearchLineEdit, TransparentToolButton, FluentIcon as FIF

from common import signalBus
from .history_interface import SearchHistoryInterface
from .search_widget import SearchWidget


class SearchInterface(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.isLoad = False
        self.verticalLayout = QVBoxLayout(self)
        self.backBtn = TransparentToolButton(FIF.RETURN, self)
        self.searchLineEdit = SearchLineEdit(self)
        self.stackedWidget = QStackedWidget(self)
        self.historyInterface = SearchHistoryInterface(self)
        self.searchWidget = SearchWidget(self)

        self.__initWidgets()
        self.__connectSignals()

    def __initWidgets(self):
        self.setObjectName("SearchInterface")
        self.searchLineEdit.setPlaceholderText('请输入关键字搜索')
        self.searchLineEdit.setClearButtonEnabled(True)
        self.searchLineEdit.setFixedWidth(500)
        self.backBtn.setGeometry(11, 11, 40, 36)
        self.backBtn.hide()

        self.stackedWidget.addWidget(self.historyInterface)
        self.stackedWidget.addWidget(self.searchWidget)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setContentsMargins(11, 11, 0, 11)
        self.verticalLayout.addWidget(self.searchLineEdit, 1, Qt.AlignmentFlag.AlignHCenter)
        self.verticalLayout.addWidget(self.stackedWidget)

    def __connectSignals(self):
        self.searchLineEdit.searchSignal.connect(self.onSearch)
        signalBus.searchChanged.connect(self.onSearch)
        self.backBtn.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(0))
        self.stackedWidget.currentChanged.connect(self.onStackedWidgetChanged)

    def onStackedWidgetChanged(self, index: int):
        if index == 0:
            self.backBtn.hide()
        else:
            self.backBtn.show()

    def onSearch(self, keyword: str):
        # qevent_manager.addSqlTaskToPool(add_search_history, keyword, slot=signalBus.updateHistoryTagSig.emit)
        self.stackedWidget.setCurrentWidget(self.searchWidget)
        self.searchWidget.clear()
        self.searchLineEdit.setText(keyword)
        self.searchWidget.search(keyword)

    def init(self):
        if not self.isLoad:
            self.historyInterface.load()
            self.isLoad = True
